/*
 * Copyright 2023-2085 xujin <ceo@itgrail.com>
 *
 * Licensed under the Grail License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://itgrail.com/docs?id=3&catalogId=87
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.itgrail.pilot.app.command;

import com.google.common.base.Preconditions;
import com.itgrail.pilot.app.command.cmo.UpdateUserPasswordCmd;
import com.itgrail.pilot.infrastructure.tunnel.db.dao.UserMapper;
import com.itgrail.pilot.infrastructure.tunnel.db.dataobject.UserDO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.itgrail.grail.cqrs.annotation.CmdHandler;
import com.itgrail.grail.cqrs.command.CommandExecutorI;
import com.itgrail.grail.dto.ResultData;
import com.itgrail.grail.shiro.util.MD5;

@CmdHandler
public class UpdateUserPasswordCmdExe implements CommandExecutorI<ResultData<Void>, UpdateUserPasswordCmd> {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResultData execute(UpdateUserPasswordCmd cmd) {
        check(cmd);
        UserDO userDO = userMapper.findUserByUserId(cmd.getUserId());
        if (null == userDO) {
            return ResultData.fail("UP404", "需要修改密码的用户不存在");
        }
        if (StringUtils.isEmpty(userDO.getPassword())) {
            return ResultData.fail("UP405", "旧密码不存在");
        }
        if (!userDO.getPassword().equals(MD5.md5(cmd.getOldPassword()))) {
            return ResultData.fail("UP406", "旧密码错误，请联系管理员处理!");
        }
        userDO.setPassword(MD5.md5(cmd.getNewPassword()));
        userMapper.updateById(userDO);
        return ResultData.success();

    }

    protected boolean check(UpdateUserPasswordCmd cmd) {
        Preconditions.checkNotNull(cmd, "cmd不能为null");
        Preconditions.checkNotNull(cmd.getUserId(), "userId不能为null");
        Preconditions.checkNotNull(cmd.getNewPassword(), "新密码不能为空");
        Preconditions.checkNotNull(cmd.getOldPassword(), "旧密码不能为空");
        return true;
    }
}
